package com.xyz.controller;

import com.xyz.aop.Param;
import com.xyz.service.MessageService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.LoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("message")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private MessageService messageService;

    /**
     * 创建SSE连接
     */
    @GetMapping(path = "/connect/{token}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse(
            @PathVariable String token
    ) {
        System.out.println(token);
        SseEmitter se = messageService.connect(token);
        logger.info("SSE新用户连接", token);
        return se;
    }

    @PostMapping("selectMessage")
    public DataResult selectMessage(
            LoginInfo li,
            @Param(type = Param.ParamType.POSITIVE_INTEGER) String pageNum,
            @Param(type = Param.ParamType.POSITIVE_INTEGER) String pageSize,
            @Param(type = Param.ParamType.POSITIVE_INTEGER) String messageType
    ) {
        try {
            return messageService.selectMessage(
                    li, Integer.parseInt(pageNum), Integer.parseInt(pageSize),
                    Integer.parseInt(messageType)
            );
        } catch (Exception e) {
            logger.error("selectMessage", e);
            return DataResult.build9500();
        }
    }

    @PostMapping("updateMessageState")
    public DataResult updateMessageState(
            LoginInfo li,
            @Param String id
    ) {
        try {
            return messageService.updateMessageState(li, Long.parseLong(id));
        } catch (Exception e) {
            logger.error("updateMessageState", e);
            return DataResult.build9500();
        }
    }

}
